package com.nulldev.util.fileformats.ftf;

import java.util.Date;

import com.nulldev.util.io.MD5Utils;
import com.nulldev.util.java.ReturnableFunction;
import com.nulldev.util.java.date.DateUtil;
import com.nulldev.util.lang.json.Json;
import com.nulldev.util.lang.json.JsonObject;
import com.nulldev.util.lang.json.JsonValue;
import com.nulldev.util.net.IPUtil;
import com.nulldev.util.os.CPUUtil;
import com.nulldev.util.os.GPUUtil;
import com.nulldev.util.os.OSUtil;
import com.nulldev.util.other.ArrayUtils;
import com.nulldev.util.uri.URIUtil;

public enum FTFMetadata {
	DATE_OF_CREATION("date_create", new ReturnableFunction<Date>() {
		@Override
		public Date getItem() {
			return DateUtil.get();
		}	
	}),
	
	USER_UID("uid", new ReturnableFunction<String>() {
		@Override
		public String getItem() {
			final String[] args = new String[] {OSUtil.getOperatingSystemString(), IPUtil.getInternetLocalIP_Safe(), CPUUtil.parse().toString(), GPUUtil.parse().toString()};
			return MD5Utils.getMD5Hex(ArrayUtils.StringArrayUtils.addFrom(args, 0));
		}
	}),
	
	GEOLOCATION("geo", new ReturnableFunction<String>() {

		@Override
		public String getItem() {
			try {
				final JsonValue parsed = Json.parse(
					URIUtil.downloadPage(URIUtil.safeCreate("http://geoip.nekudo.com/api/")));
				final JsonObject location = parsed.asObject().get("location").asObject();
				return location.getFloat("latitude", -1) + "," + location.getFloat("longitude", -1);
			}catch (Exception e) {
				return "-1,-1";
			}
		}
		
	});
	;
	
	private final String key;
	private final ReturnableFunction function;
	private <T> FTFMetadata(final String metadataKey, final ReturnableFunction<T> function) {
		this.key = metadataKey;
		this.function = function;
	}
	
	public String getKey() {
		return this.key;
	}
	
	public <T> T getItem() {
		return (T) this.function.getItem();
	}
}
